package com.example.limiting.taskmanager2;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;

public class LoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void Login(View view){
//        Toast.makeText(getApplicationContext(), "Login", Toast.LENGTH_SHORT).show();
//        Intent intent = new Intent();
//        intent.setClass(LoginActivity.this,MainActivity.class);
//        startActivity(intent);
        EditText userId = (EditText) findViewById(R.id.userID);
        EditText password = (EditText) findViewById(R.id.pwd);
//        Log.e("Login",userId.getText().toString()+" "+password.getText().toString());

        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            new LoginTask().execute(userId.getText().toString(),password.getText().toString());
        } else {
            Toast.makeText(LoginActivity.this,"请检查你的网络!",Toast.LENGTH_SHORT).show();
        }


    }

    private class LoginTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            HttpHelper httpHelper = new HttpHelper(LoginActivity.this);
            String result = null;
            try {
               result = httpHelper.checkAccount(params[0],params[1]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
//            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();

            Log.e("LoginTask", result);
            if (result.isEmpty()){
                Toast.makeText(LoginActivity.this,"网络状态不好，请重试！",Toast.LENGTH_SHORT).show();
            }else{
                JSONTokener jsonParser = new JSONTokener(result);
                try {
                    JSONObject body = (JSONObject) jsonParser.nextValue();
                    int status = body.getInt("status");
                    JSONObject data = body.getJSONObject("data");
                    String resu = data.getString("result");
                    if (resu.equals("true")){

                        Toast.makeText(LoginActivity.this,"欢迎登陆 "+data.getString("realname"),Toast.LENGTH_SHORT).show();

                        String userId = data.getString("userId");

                        SharedPreferences sharedPref = getSharedPreferences("userId", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.putString("userId",userId);
                        editor.commit();

                        Intent intent = new Intent();
                        intent.setClass(LoginActivity.this, MainActivity.class);
                        intent.putExtra("userId",userId);
                        startActivity(intent);
                    }else{
                        Toast.makeText(LoginActivity.this,"用户名或密码错误！",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }



        }
    }
}
